package fun.ticsmyc.tmall.item.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import fun.ticsmyc.tmall.item.pojo.Comment;
import fun.ticsmyc.tmall.item.service.CommentService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 监听消息队列， Comment数据异步写入Mysql
 * @author Ticsmyc
 * @date 2020-05-26 11:54
 */
@Component
public class CommentListener {

    @Autowired
    private CommentService commentService;

    @Autowired
    private ObjectMapper mapper;

    @RabbitListener(bindings = @QueueBinding(
            value=@Queue(value="XDMALL.COMMENT.MODIFY.QUEUE",durable = "true"),
            exchange=@Exchange(value="XDMALL.COMMENT.EXCHANGE",ignoreDeclarationExceptions = "true",type= ExchangeTypes.TOPIC),
            key={"comment"}
    ))
    public void modifyComment(Map<String,String> msg){
        String method = msg.get("method");
        if("insert".equals(method)){
            Comment comment = null;
            try {
                comment = mapper.readValue(msg.get("comment"), Comment.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //插入请求
            if(comment != null){
                this.commentService.insertComment(comment);
            }
        }else if("update".equals(method)){
            //更新评论
            Comment comment = null;
            try {
                comment = mapper.readValue(msg.get("comment"), Comment.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(comment != null){
                this.commentService.modifyCommentById(comment.getId(),comment.getContent());
            }
        }else if("delete".equals(method)){
            Long commentId = Long.parseLong(msg.get("commentId"));
            this.commentService.deleteCommentById(commentId);
        }

    }

}
